package com.lagou.controller;

import cn.hutool.core.util.ObjectUtil;
import com.lagou.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpSession;
import java.util.Calendar;

@Controller
public class LoginController {

    @Autowired
    private UserService userService;

    @RequestMapping("/")
    public String index(Model model){
        model.addAttribute("currentYear", Calendar.getInstance().get(Calendar.YEAR));
        return "login";
    }


    @RequestMapping("login")
    public String login(Model model, String name, String password, HttpSession session) {
        // 合法用户，信息写入session，同时跳转到系统主页面

        if(ObjectUtil.isNotEmpty(userService.login(name, password))) {
            System.out.println("合法用户");
            model.addAttribute("sessionId", session.getId());
            String username = name + System.currentTimeMillis();
            model.addAttribute("username", username);
            session.setAttribute("username",username);
            return "index";
        }else{
            // 非法用户返回登录页面
            System.out.println("非法，跳转");
            return "redirect:/";
        }
    }


}
